﻿using mvcForum.Core;
using mvcForum.Core.Interfaces.Data;
using mvcForum.Web.Controllers;
using mvcForum.Web.Extensions;
using System;
using System.Web.Mvc;
using AccessMaskVM = mvcForum.Web.Areas.ForumAPI.ViewModels.AccessMask;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class AccessMaskController : BaseAPIController {

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Create(AccessMaskVM model, String mode) {
			if (ModelState.IsValid) {
				Board board = this.GetRepository<Board>().Read(model.BoardId);
				// TODO: Access!!!

				AccessMask mask = new AccessMask(board, model.Name, model.AccessFlag);
				this.GetRepository<AccessMask>().Create(mask);

				this.Context.SaveChanges();

				return new HttpStatusCodeResult(200);
			}

			return new HttpStatusCodeResult(500, ModelState.ErrorString());
		}

		public ActionResult Read(Int32 id, String mode) {
			// TODO: Access!
			AccessMask mask = this.GetRepository<AccessMask>().Read(id);
			return this.CustomJson(new AccessMaskVM {
				Id = mask.Id,
				Name = mask.Name,
				AccessFlag = mask.AccessFlag,
				BoardId = mask.Board.Id
			});
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Update(AccessMaskVM model, String mode) {
			if (ModelState.IsValid) {
				AccessMask mask = this.GetRepository<AccessMask>().Read(model.Id);
				// TODO: Access!!

				mask.Name = model.Name;
				mask.AccessFlag = model.AccessFlag;

				this.Context.SaveChanges();

				return new HttpStatusCodeResult(200);
			}

		    return new HttpStatusCodeResult(500, ModelState.ErrorString());
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Delete(Int32 id, String mode) {
			IRepository<AccessMask> maskRepo = this.GetRepository<AccessMask>();
			AccessMask mask = maskRepo.Read(id);

			// TODO: Access!!
			//Board board = mask.Board;

			// TODO: Delete from group/forum relations
			maskRepo.Delete(mask);

			this.Context.SaveChanges();

			return new HttpStatusCodeResult(200);
		}
	}
}